2
2
.
.
1
1
0
0
.
.
2
2
@
@
J
J
s
s
o
o
n
n
S
S
e
e
r
r
i
i
a
a
l
l
i
i
z
z
e
e
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to create custom Serializer to return DTO as JSON from Controller.
Serializer is
implemented as class PersonDTOSerializer extends JsonSerializer<PersonDTO>
attached to PersonDTO with @JsonSerialize(using = PersonDTOSerializer.class)
called when Controller returns PersonDTO
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller, @RequestMapping, Tomcat Server
MyController
PersonDTO
POSTMAN
PersonDTO
Serializer
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_json_serializer (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
Create Class: PersonDTOSerializer.java (inside package DTO)
Create Class: PersonDTO.java (inside package DTO)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
PersonDTOSerializer.java
package com.ivoronline.springboot_json_serializer.DTO;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class PersonDTOSerializer extends JsonSerializer<PersonDTO> {
@Override
public void serialize(PersonDTO personDTO, JsonGenerator jsonGenerator, SerializerProvider provider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("First Name", personDTO.name);
jsonGenerator.writeNumberField("Age" , personDTO.age);
jsonGenerator.writeEndObject();
}
}
PersonDTO.java
package com.ivoronline.springboot_json_serializer.DTO;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = PersonDTOSerializer.class)
public class PersonDTO {
public String name;
public Integer age;
}
MyController.java
package com.ivoronline.springboot_json_serializer.controllers;
import com.ivoronline.springboot_json_serializer.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/GetPerson")
public PersonDTO addPerson() {
//CREATE PERSON
PersonDTO PersonDTO = new PersonDTO();
PersonDTO.name = "John";
PersonDTO.age = 20;
//RETURN PERSON AS JSON (SERIALIZED)
return PersonDTO;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/GetPerson
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>